import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

import '../dio_manager.dart';
import '../utils/log_util.dart';

void _print(Object obj) {
  if (kDebugMode || kReleaseMode) {
    debugPrint(obj.toString());
  }
}

class LogsInterceptor extends Interceptor {
  final Map<RequestOptions, int> _costDuration = {};

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (kDebugMode || kProfileMode) {
      if (dio.logPrint) {
        String method = options.method;
        _print("$method method: ${options.baseUrl}${options.path}, "
            "queryParameters: ${options.queryParameters}, headers: ${options.headers}");
      }
    }
    _costDuration[options] = DateTime.now().millisecondsSinceEpoch;
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (kDebugMode || kProfileMode) {
      if (dio.logPrint) {
        int? start = _costDuration[response.requestOptions];
        int cost = -1;
        if (null != start) {
          cost = DateTime.now().millisecondsSinceEpoch - start;
        }
        final resStr = response.toString();
        if (-1 != cost) {
          LogUtil.d("response cost ${cost}ms, data==$resStr");
        } else {
          LogUtil.d("response==$resStr");
        }
      }
    }
    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    if (kDebugMode || kProfileMode) {
      if (dio.logPrint) {
        final resStr = err.toString();
        _print(resStr);
      }
    }
    super.onError(err, handler);
  }
}
